import React, { useRef } from 'react';
import ReactECharts from 'echarts-for-react';
import ChartCard from './ChartCard';

interface PieChartData {
  name: string;
  value: number;
  color?: string;
}

interface PieChartProps {
  title: string;
  subtitle?: string;
  data: PieChartData[];
  loading?: boolean;
  height?: number;
  radius?: string | [string, string];
  center?: [string, string];
  showLegend?: boolean;
  showLabel?: boolean;
  showLabelLine?: boolean;
  roseType?: 'radius' | 'area' | false;
  onRefresh?: () => void;
  className?: string;
  style?: React.CSSProperties;
}

export default function PieChart({
  title,
  subtitle,
  data,
  loading = false,
  height = 300,
  radius = ['40%', '70%'],
  center = ['50%', '50%'],
  showLegend = true,
  showLabel = true,
  showLabelLine = true,
  roseType = false,
  onRefresh,
  className,
  style
}: PieChartProps) {
  const chartRef = useRef<any>(null);

  // 生成颜色
  const colors = [
    '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
    '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#ff9f7f'
  ];

  const processedData = data.map((item, index) => ({
    ...item,
    itemStyle: {
      color: item.color || colors[index % colors.length]
    }
  }));

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      show: showLegend,
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.name),
      textStyle: {
        color: '#666'
      }
    },
    series: [
      {
        name: title,
        type: 'pie',
        radius,
        center,
        roseType,
        data: processedData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: showLabel,
          formatter: '{b}: {d}%',
          color: '#666'
        },
        labelLine: {
          show: showLabelLine
        },
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx: number) {
          return Math.random() * 200;
        }
      }
    ]
  };

  const handleExport = () => {
    if (chartRef.current) {
      const echartsInstance = chartRef.current.getEchartsInstance();
      const base64 = echartsInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      });
      
      // 创建下载链接
      const link = document.createElement('a');
      link.download = `${title}-${new Date().toISOString().split('T')[0]}.png`;
      link.href = base64;
      link.click();
    }
  };

  const handleFullscreen = () => {
    if (chartRef.current) {
      const echartsInstance = chartRef.current.getEchartsInstance();
      const base64 = echartsInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      });
      
      // 在新窗口中显示图表
      const newWindow = window.open('', '_blank');
      if (newWindow) {
        newWindow.document.write(`
          <html>
            <head><title>${title}</title></head>
            <body style="margin:0;padding:20px;text-align:center;">
              <h2>${title}</h2>
              <img src="${base64}" style="max-width:100%;height:auto;" />
            </body>
          </html>
        `);
      }
    }
  };

  return (
    <ChartCard
      title={title}
      subtitle={subtitle}
      loading={loading}
      onRefresh={onRefresh}
      onExport={handleExport}
      onFullscreen={handleFullscreen}
      className={className}
      style={style}
    >
      <ReactECharts
        ref={chartRef}
        option={option}
        style={{ height: `${height}px`, width: '100%' }}
        notMerge={true}
        lazyUpdate={true}
      />
    </ChartCard>
  );
}

// 导出类型
export type { PieChartProps, PieChartData };